package com.type.service;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.StringReader;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.annotation.Resource;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.springframework.stereotype.Service;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.xml.sax.InputSource;

import com.type.dao.CorpDAO;
import com.type.dao.ProductDAO;
import com.type.vo.CorpVO;
import com.type.vo.ProductVO;

@Service("TypeFourService")
public class TypeFourService {
	private String apiKey="b713fbc8e50d67ffb1373501370151";
	private String target="post";
	private String reqUrl="http://biz.epost.go.kr/KpostPortal/openapi";
	private String str="";
	
	@Resource(name="productDAO")
	private ProductDAO productDAO;
	@Resource(name="corpDAO")
	private CorpDAO corpDAO;
	
	public String insertProduct(HashMap map) throws SQLException{
		ProductVO p = new ProductVO();
		p.setP_name((String) map.get("pName"));
		p.setP_ea(Integer.parseInt((String)map.get("pEa")));
		p.setP_price((String) map.get("pPrice"));
		p.setP_corp_name((String) map.get("pCorp"));
		CorpVO temp = corpDAO.selectCorpByName((String) map.get("pCorp"));
		p.setP_corp_id(temp.getC_id());
		
		productDAO.insertProduct(p);
		
		System.out.println(p.toString());
		return "";
	}
	
	public String insertCorperation(HashMap map) throws SQLException{
		CorpVO co = new CorpVO();
		String str;
		co.setC_name((String) map.get("cName"));
		str = (String) map.get("cRegNum1") + (String) map.get("cRegNum2") + (String) map.get("cRegNum3");
		co.setC_regnum(str);
		str = (String) map.get("cPhone1") + (String) map.get("cPhone2") + (String) map.get("cPhone3");
		co.setC_phone(str);
//		str = (String) map.get("cPost1") + (String) map.get("cPost2");
//		co.setC_post(str);
//		str = (String) map.get("cAddr1") + (String) map.get("cAddr2");
		str = (String) map.get("cLoc");
		co.setC_address(str);
		co.setC_ceo((String) map.get("cCeo"));
		System.out.println(co.toString());
		corpDAO.insertCorp(co);
		return "";
	}
	
	
	/*@SuppressWarnings({ "unchecked", "rawtypes" })
	public ArrayList getAddress(String str) throws Exception{
		ArrayList addressInfo = new ArrayList();
		this.str=str;
		HttpURLConnection conn = null;
		
		try {
			StringBuffer sb = new StringBuffer();
			sb.append(reqUrl);
			sb.append("?regkey="+apiKey+"&target="+target+"&query=");
			sb.append(URLEncoder.encode(str,"EUC-KR"));
			String query = sb.toString();
			
			URL url = new URL(query);
			conn = (HttpURLConnection) url.openConnection();
			conn.setRequestProperty("accept-language", "ko");
			
			DocumentBuilder docBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
			byte[] bytes = new byte[4096];
			InputStream in = conn.getInputStream();
			ByteArrayOutputStream baos = new ByteArrayOutputStream();
			
			while(true){
				int red = in.read(bytes);
				if(red < 0){
					break;
				}
				baos.write(bytes, 0, red);
			}
			
			String xmlData = baos.toString("euc-kr");
			baos.close();
			in.close();
			conn.disconnect();
			
			Document doc = docBuilder.parse(new InputSource(new StringReader(xmlData)));
			Element el = (Element) doc.getElementsByTagName("itemlist").item(0);
			
			for(int i = 0; i < el.getChildNodes().getLength(); i++) {
				Node node = el.getChildNodes().item(i);
				if(!node.getNodeName().equals("item")){
					continue;
				}
				String address = node.getChildNodes().item(1).getFirstChild().getNodeValue();
				String post = node.getChildNodes().item(3).getFirstChild().getNodeValue();
				
				String regAddr = regAddress(address);
				if(regAddr!=null){
					addressInfo.add(new String[]{post.substring(0, 3),post.substring(3),address, regAddr});
				}
			}
		} catch (Exception e){
			throw new Exception(e.getMessage());
		} finally {
			try{ if(conn!=null) conn.disconnect();}
			catch (Exception e){}
			
		}
		
		return addressInfo;
	}

	private String regAddress(String testString) {
		Matcher m;
		Pattern p;
		String pattern1 = "\\d{1,5}~\\d{1,5}동?";
		String temp = "[^"+str+"\\s]{"+str.length()+"}";
		String pattern2 = "\\s"+temp+"\\d?[동면읍]\\s";
		temp = "[^"+str.charAt(0)+"\\s]["+str.substring(1)+"]";
		String pattern3 = "\\s"+temp+"\\d?[동면읍]\\s";
		
		System.out.println("pettern2"+pattern2);
		System.out.println("pettern3"+pattern3);
		
		String reg[] = { pattern1,pattern2,pattern3 };

		for (String s : reg) {
			p = Pattern.compile(s);
			m = p.matcher(testString);

			// 정규식에 걸린 구문
			if (m.find()) {
				
				if (s.equals(pattern1)) {
//					System.out.println(m.group() + "##");
					testString = m.replaceAll("");
				} else if(s.equals(pattern2)){
					System.out.println(testString);
					System.out.println(m.group() + "@@");
					return null;
				} else {
					System.out.println(testString);
					System.out.println(m.group() + "&&");
					return null;
				}
			}
		
		}

		return testString;
	}*/

	public ArrayList getCList() {
		return corpDAO.selectCNameList();
	}

}
